package com.ruoyi.business.sundry.service.impl;


import com.ruoyi.business.sundry.domain.vo.JbProductRecipeHistoryStatistics;
import com.ruoyi.business.sundry.service.JbProductRecipeHistoryService;
import org.springframework.stereotype.Service;
import com.ruoyi.business.base.JoBaseServiceImpl;
import com.ruoyi.business.sundry.mapper.JbProductRecipeHistoryMapper;
import com.ruoyi.business.sundry.domain.JbProductRecipeHistory;

import java.util.List;
import java.util.StringJoiner;

/**
 * 商品配方历史Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-11
 */
@Service
public class JbProductRecipeHistoryServiceImpl
        extends JoBaseServiceImpl<JbProductRecipeHistoryMapper, JbProductRecipeHistory>
        implements JbProductRecipeHistoryService
{

    @Override
    public List<JbProductRecipeHistoryStatistics> historyStatistics(JbProductRecipeHistoryStatistics statistics)
    {
        StringJoiner sql=new StringJoiner(" ").add("""
                SELECT
                	jprh.id,
                	jprh.inventory_cost,
                	jprh.real_time_cost,
                	t.yearMonth\s
                FROM
                	jb_product_recipe_history jprh
                	INNER JOIN (
                	SELECT
                		DATE_FORMAT( prh.create_time, '%Y-%m' ) AS yearMonth,
                		MAX( prh.id ) AS maxId\s
                	FROM
                		jb_product_recipe_history prh\s
                	WHERE
                		del_flag = 0\s            
                """);
        sql.add(joSqlUtil.sqlIf(" AND product_recipe_id =#{productRecipeId} ",statistics.getProductRecipeId()));
        sql.add(joSqlUtil.sqlIf(" AND commodity_id = #{commodityId} ",statistics.getCommodityId()));
        sql.add(joSqlUtil.sqlIf(" AND YEAR ( prh.create_time )= #{yearMonth} ",statistics.getYearMonth()));
        sql.add("""
                GROUP BY
                		yearMonth\s
                	) t ON jprh.id = t.maxId
                """);
        String s = joSqlUtil.sqlJson(sql.toString(), statistics);
        return joSqlUtil.jsonToEntity(baseMapper.findJson(s),JbProductRecipeHistoryStatistics.class);
    }
}
